/**
 * <p><b>Title:</b> SystemConfigController.java </p>
 * @Package com.wondertek.oes.bc.service.controller
 */
package com.wondertek.poms.setting.controller;


import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.controller.BaseController;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.ISystemConfigService;
import com.wondertek.poms.dao.po.SystemConfig;
import com.wondertek.poms.setting.vo.SystemConfigVo;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * <p><b>SystemConfigController Description:</b> Controller层实现</p>
 * @author wzq
 * <p><b>DATE</b> 2019-06-27 13:48:26</p>
 */
@Api("系统配置")
@RestController
@Scope("prototype")
@RequestMapping(value="/sys-config")
public class SystemConfigController extends BaseController {

    @Autowired
    private ISystemConfigService systemConfigService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * <p><b>Title:</b> list</p>
     * <p><b>Description:</b> 系统配置列表</p>
     *
     * @param request
     * @param systemConfigVo
     * @param page
     * @param rows
     * @param sidx
     * @param sord
     * @return
     * @author
     */
    @MethodLog(module = "系统配置列表")
    @ApiOperation("列表")
    @GetMapping("/list")
    @ResponseBody
    public ResultBean list(HttpServletRequest request,
                           SystemConfigVo systemConfigVo,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "20") int rows,
                           @RequestParam(defaultValue = "id") String sidx,
                           @RequestParam(defaultValue = "asc") String sord) {
        SystemConfig systemConfig = new SystemConfig();
        BeanUtils.copyProperties(systemConfigVo, systemConfig);

        Page<SystemConfig> pages = systemConfigService
                .findAllData(systemConfig, page, rows, sord, sidx);
        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
    }

    /**
     * <p><b>Title:</b> add</p>
     * <p><b>Description:</b> 系统配置新增</p>
     *
     * @param systemConfigVo
     * @return
     * @author
     */
    @MethodLog(module = "系统配置新增", insertDB = true)
    @ApiOperation("新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ckey", required = true),
            @ApiImplicitParam(name = "value", required = true),
            @ApiImplicitParam(name = "description", required = true),
            @ApiImplicitParam(name = "version", required = true),
    })
    @PostMapping(value = "/add")
    @ResponseBody
    public ResultBean add(@RequestBody SystemConfigVo systemConfigVo) {
        if (systemConfigVo.getValue().contains("，")) {
            return ResultBean.error("您输入的值的逗号必须为英文逗号");
        }
        List<String> messageList = ValidateFilter.getFilterMessage(systemConfigVo, Constants.VALIDATE_DEFAULT);
        if (!messageList.isEmpty()) {
            return ResultBean.error(messageList.toString());
        }

        if (isRepeat(systemConfigVo))
            return ResultBean.error("系统配置键" + MessageCodes.get(MessageCodes.M980014));

        SystemConfig systemConfig = new SystemConfig();
        BeanUtils.copyProperties(systemConfigVo, systemConfig);
        systemConfig.setDeleted(0);
        systemConfigService.save(systemConfig);
        return ResultBean.ok(systemConfig);
    }

    /**
     * <p><b>Title:</b> isRepeat</p>
     * <p><b>Description:</b> 判断名称是否重复</p>
     *
     * @param systemConfigVo
     * @author
     */
    private boolean isRepeat(SystemConfigVo systemConfigVo) {
        SystemConfig temp = new SystemConfig();
        temp.setCkey(systemConfigVo.getCkey());
        Optional<SystemConfig> systemConfigOpt = systemConfigService.findOne(Example.of(temp));
        if (systemConfigOpt.isPresent()) {
            SystemConfig systemConfig = systemConfigOpt.get();
            if (systemConfigVo.getId() != null && !systemConfigVo.getId().equals(systemConfig.getId()))
                return true;
            else return systemConfigVo.getId() == null;
        }
        return false;
    }

    /**
     * <p><b>Title:</b> get</p>
     * <p><b>Description:</b> 系统配置详情</p>
     *
     * @param id
     * @return
     * @author
     */
    @MethodLog(module = "系统配置详情")
    @ApiOperation("详情")
    @ApiImplicitParam(name = "id", required = true, paramType = "query", dataType = "Long")
    @GetMapping(value = "/get")
    @ResponseBody
    public ResultBean get(Long id) {
        SystemConfig systemConfig = systemConfigService.get(id);
        return ResultBean.ok(systemConfig);
    }

    /**
     * <p><b>Title:</b> update</p>
     * <p><b>Description:</b> 系统配置变更</p>
     *
     * @param systemConfigVo
     * @return
     * @author
     */
    @MethodLog(module = "系统配置变更", insertDB = true, opterate = 2)
    @ApiOperation("变更")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true),
            @ApiImplicitParam(name = "ckey", required = true),
            @ApiImplicitParam(name = "value", required = true),
            @ApiImplicitParam(name = "description", required = true),
            @ApiImplicitParam(name = "version", required = true),
    })
    @PutMapping(value = "/edit")
    @ResponseBody
    public ResultBean update(@RequestBody SystemConfigVo systemConfigVo) {
        if (systemConfigVo.getValue().contains("，")) {
            return ResultBean.error("您输入的值的逗号必须为英文逗号");
        }
        List<String> messageList = ValidateFilter.getFilterMessage(systemConfigVo, Constants.VALIDATE_UPDATE);
        if (!messageList.isEmpty()) {
            return ResultBean.error(messageList.toString());
        }
        SystemConfig systemConfig = systemConfigService.get(systemConfigVo.getId());
        BeanUtils.copyProperties(systemConfigVo, systemConfig);
        systemConfigService.save(systemConfig);
        return ResultBean.ok();
    }

    /**
     * <p><b>Title:</b> delete</p>
     * <p><b>Description:</b> 删除系统配置</p>
     *
     * @param id
     * @return
     * @author
     */
    @MethodLog(module = "删除系统配置", insertDB = true, opterate = 3)
    @ApiOperation("删除")
    @ApiImplicitParam(name = "id", required = true, paramType = "query", dataType = "Long")
    @DeleteMapping(value = "/del")
    @ResponseBody
    public ResultBean delete(Long id) {
        SystemConfig config = systemConfigService.findById(id);
        systemConfigService.deleteById(config);
        return ResultBean.ok();
    }

    /**
     * <p><b>Title:</b> findAllByType</p>
     * <p><b>Description:</b> 根据type查询系统配置全部数据</p>
     *
     * @param ckey
     * @param request
     * @return
     * @author
     */
    @MethodLog(module = "根据ckey查询系统配置全部数据")
    @ApiOperation("根据ckey查询全部数据")
    @ApiImplicitParam(name = "ckey", required = true, paramType = "query", dataType = "String")
    @GetMapping("/all")
    public ResultBean findAllByType(String ckey, HttpServletRequest request) {
        if (ckey == null || ckey.equals("")) {
            return ResultBean.error("参数不能为空");
        }
        SystemConfig systemConfigs = systemConfigService.findAllBykey(ckey);
        if (systemConfigs == null) {
            return ResultBean.error("没有此系统配置");
        }
        return ResultBean.ok(systemConfigs);
    }

    @ApiOperation("系统配置缓存刷新")
    @GetMapping(value = "/cache-refresh")
    @ResponseBody
    @MethodLog(module = "系统配置缓存刷新", insertDB = true, opterate = 2)
    public ResultBean findByLikeType() {
        Set<String> keys = redisTemplate.keys(Constants.REDIS_KEY_SYSTEM_CKEY + "*");
        redisTemplate.delete(keys);
        SystemConfig systemConfig = new SystemConfig();
        systemConfig.setDeleted(0);
        List<SystemConfig> sysConfigList = systemConfigService.findAll(Example.of(systemConfig));
        for (SystemConfig config : sysConfigList) {
            systemConfigService.cacheRefresh(config.getCkey(), sysConfigList);
        }
        return ResultBean.ok();
    }
}
